package info.openlvb.openface.client.handler;

import info.openlvb.openface.client.base.Machine;
import info.openlvb.openface.client.base.machine.AddMachinePanel;
import info.openlvb.openface.client.service.LdapService;
import info.openlvb.openface.client.service.LdapServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;

public class AddMachineListener extends ButtonListenerAdapter{

	private AddMachinePanel amp;
	private final LdapServiceAsync ldapService = GWT.create(LdapService.class);

	public AddMachineListener(AddMachinePanel amp){
		this.amp = amp;
	}
	public void onClick(Button button, EventObject e) {
		ldapService.searchMachineByUid(amp.getMachine_nm().getText(), new AsyncCallback<Machine>() {
			public void onFailure(Throwable caught) {
				MessageBox.alert("probleme de backend");
			}
			public void onSuccess(Machine result) {
				if(result!=null){
					MessageBox.alert("l'ordinateur existe deja");
				}else{
					ldapService.addMachine(amp.getMachine_nm().getText(), amp.getMachine_desc().getText(), 
							new AsyncCallback<Void>() {
						public void onSuccess(Void result) {
							MessageBox.alert("Succès ...", "la machine a été ajoutée !");
							
						}
						public void onFailure(Throwable caught) {
							MessageBox.alert("probleme ...", "probleme de communication avec le backend");
						}
					});
					amp.getMachine_nm().setValue("");
					amp.getMachine_desc().setValue("");
				}
			}
		});

	}
}
